<template>
  <button @click="onHandClick">
    <img :src="activeSrc" />
  </button>
</template>

<script setup lang="ts" name="ApngStatus">
import { equ } from '../../../package-env'
const props = withDefaults(defineProps<{ status?: number, name: string, type?: string }>(), { status: 0, name: '', type: '' })
const emit = defineEmits(['hand'])

const getPath = (status) => {
  return new URL(`../../assets/apng/${props.name}/${status}.png`, import.meta.url).href
}

const svgas = [
  { static: getPath('1.static'), move: getPath('1.move') },
  { static: getPath('2.static'), move: getPath('2.move') }
]
const music = new Audio(new URL(`../../assets/music/button-feedback.mp3`, import.meta.url).href)
const status = ref('static')
const activeSrc = computed(() => svgas[props.status][status.value])

// 切换
let timer
const switchState = async () => {
  if (timer) clearTimeout(timer)
  status.value = 'move'
  timer = setTimeout(() => {
    status.value = 'static'
    music.pause()
    music.currentTime = 0
  }, 600)
  music.volume = equ === 'pc' ? 0.5 : 0.1
  music.play()
}

watch(() => props.status, () => {
  if (props.type !== 'static') switchState()
})

const onHandClick = () => {
  if (props.type === 'static') {
    switchState()
    emit('hand')
  }
}
</script>